package com.yonder.security;

import com.yonder.pojo.Permission;
import com.yonder.pojo.Role;
import com.yonder.pojo.User;
import com.yonder.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * @ClassName SpringSecurityUserService
 * @Description TODO
 * @Author zxs
 * @Date 2021/3/23 16:54
 * Version 1.0
 *
 *
 * 自定义认证授权类
 */

@Component
public class SpringSecurityUserService implements UserDetailsService {

    //注意：此处要通过dubbo远程调用用户服务
    @Autowired
    private UserService userService;

    //根据用户名查询用户信息
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        /*
         * 根据用户名查询用户信息，例如：用户是什么角色、拥有什么权限
         * */
        User user = userService.findUserByUsername(username);

        if (user == null) {
            return null;
        }


        List<GrantedAuthority> list = new ArrayList<GrantedAuthority>();

        //获取用户所具有的角色存放到set集合中
        Set<Role> roles = user.getRoles();

        for (Role role : roles) {
            //获取各个角色对应的权限
            Set<Permission> permissions = role.getPermissions();

            for (Permission permission : permissions) {

                //授权（针对权限）
                list.add(new SimpleGrantedAuthority(permission.getKeyword()));
            }
        }


        return  new org.springframework.security.core.userdetails.User(username,user.getPassword(),list);
    }
}
